
package com.haiyou.common.util.mysql;

import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * 
 * @Description: 批量操作组装
 * @author xingyuan
 * @date 2022年7月8日 上午10:44:38
 */
@Slf4j
public class BatchUtils {

	/**
	 * 分批
	 * 
	 * @param iterable 源数据
	 * @param num      每一批数量
	 * @return LinkedHashMap {batchIndex:list},batchIndex 从1开始
	 */
	public static <E> Map<Integer, List<E>> toMap(Iterable<E> iterable, int num) {
		try {
			if (Iterables.size(iterable) < 1) {
				return Collections.emptyMap();
			}
			Map<Integer, List<E>> result = Maps.newLinkedHashMap();
			Iterator<E> iterator = iterable.iterator();
			int batchIndex = 1;
			while (iterator.hasNext()) {
				List<E> list = result.computeIfAbsent(batchIndex, k -> Lists.newArrayList());
				E element = iterator.next();
				list.add(element);
				if (list.size() == num) {
					++batchIndex;
				}
			}
			return result;
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return Collections.emptyMap();
		}
	}

	/**
	 * 分批
	 * 
	 * @param iterable 源数据
	 * @param num      每一批数量
	 * @return List[List]
	 */
	public static <E> List<List<E>> toLists(Iterable<E> iterable, int num) {
		try {
			if (Iterables.size(iterable) < 1) {
				return Collections.emptyList();
			}
			List<List<E>> result = Lists.newArrayList();
			Iterator<E> iterator = iterable.iterator();
			int batchIndex = 0;
			while (iterator.hasNext()) {
				List<E> list = result.size() <= batchIndex ? null : result.get(batchIndex);
				if (list == null) {
					list = Lists.newArrayList();
					result.add(list);
				}
				E element = iterator.next();
				list.add(element);
				if (list.size() == num) {
					++batchIndex;
				}
			}
			return result;
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return Collections.emptyList();
		}
	}

}
